# postprocess.py

import json
import re
import argparse
from pathlib import Path

# 配置路径
VIDEO_DIR = Path(r"C:\Users\admin\Downloads\车载")  # 你的视频目录
OUTPUT_SUBTITLE_DIR = None  # 输出目录，如果为 None 则使用视频目录
CORRECTIONS_JSON = Path(r"C:\Users\admin\PycharmProjects\TexrEncrypy\corrections.json")  # 纠错词典路径

def load_corrections():
    with open(CORRECTIONS_JSON, "r", encoding="utf-8") as f:
        return json.load(f)

def apply_corrections_to_file(srt_path: Path, corrections: dict, overwrite: bool):
    with open(srt_path, "r", encoding="utf-8") as f:
        content = f.read()

    original = content
    for wrong, correct in corrections.items():
        pattern = re.compile(re.escape(wrong), flags=re.IGNORECASE)
        content = pattern.sub(correct, content)

    if content != original:
        if overwrite:
            with open(srt_path, "w", encoding="utf-8") as f:
                f.write(content)
            print(f"[纠正] 已处理并覆盖: {srt_path.name}")
        else:
            print(f"[纠正] 有变动但未覆盖: {srt_path.name}")
    else:
        print(f"[无变动] {srt_path.name}")

def apply_corrections(target_folder: Path = VIDEO_DIR, overwrite: bool = True):
    corrections = load_corrections()

    if OUTPUT_SUBTITLE_DIR:
        srt_files = OUTPUT_SUBTITLE_DIR.glob("*.srt")
    else:
        srt_files = target_folder.rglob("*.srt")

    for srt_path in srt_files:
        apply_corrections_to_file(srt_path, corrections, overwrite)

def parse_arguments():
    parser = argparse.ArgumentParser(description="批量纠正字幕文件中的错误")
    parser.add_argument(
        "--target-folder",
        type=Path,
        default=VIDEO_DIR,
        help="指定处理的文件夹 (默认：视频目录)"
    )
    parser.add_argument(
        "--no-overwrite",
        action="store_true",
        help="是否跳过覆盖原字幕 (默认：覆盖)"
    )
    return parser.parse_args()

if __name__ == "__main__":
    args = parse_arguments()
    overwrite = not args.no_overwrite  # 如果加了 --no-overwrite 则不覆盖
    apply_corrections(target_folder=args.target_folder, overwrite=overwrite)
